﻿#include "pch.h"
#include "Utils.h"
#include <uchardet/uchardet.h>


namespace winrt::NovelReader::Service
{
	static constexpr bool IsCRLF(wchar_t c)
	{
		return c == L'\n' || c == L'\r';
	}

	std::vector<std::wstring> SplitTextByCRLF(std::wstring const& text)
	{
		std::vector<std::wstring> result;
		size_t start = 0;
		size_t count = 0;

		for (size_t i = 0; i < text.size(); i++)
		{
			if (IsCRLF(text[i])) {
				if (count > 0) {
					result.push_back(text.substr(start, count));
				}
				start = i + 1;
				count = 0;
			}
			else {
				++count;
			}
		}
		if (count > 0) {
			result.push_back(text.substr(start, count));
		}
		return result;
	}

	bool IsDarkMode()
	{
		DWORD value = 1;
		DWORD dataSize = sizeof(value);
		if (RegGetValue(
			HKEY_CURRENT_USER,
			LR"(Software\Microsoft\Windows\CurrentVersion\Themes\Personalize)",
			LR"(AppsUseLightTheme)",
			RRF_RT_REG_DWORD,
			nullptr,
			&value,
			&dataSize) == ERROR_SUCCESS)
		{
			return value == 0;
		}

		return false;
	}

	int32_t GetTextCodePage(std::string const& input)
	{
		uchardet_t handle = uchardet_new();
		uchardet_handle_data(handle, input.c_str(), input.size());
		uchardet_data_end(handle);
		std::string encoding = uchardet_get_charset(handle);

		uchardet_delete(handle);
		if (encoding == "UTF-8")
			return CP_UTF8;
		else if (encoding == "GB18030")
			return 936;
		else
			return -1;
	}

	std::wstring ToUtf16(std::string const& multiBytesStr, UINT codePage)
	{
		int sizeNeeded = MultiByteToWideChar(codePage, 0, multiBytesStr.c_str(), -1, nullptr, 0);
		std::wstring result(sizeNeeded, 0);
		MultiByteToWideChar(codePage, 0, multiBytesStr.c_str(), -1, result.data(), sizeNeeded);
		return result;
	}

	std::string ToUtf8(std::wstring const& w)
	{
		int sizeNeeded = WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, nullptr, 0, nullptr, nullptr);
		std::string result(sizeNeeded, 0);
		WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, result.data(), sizeNeeded, nullptr, nullptr);
		return result;
	}

	std::vector<winrt::hstring> SplitTextAndAddWhiteLines(winrt::hstring const& input, int32_t whiteLines)
	{
		std::wistringstream inputStream{ input.c_str() };
		std::vector<winrt::hstring> result; 
		std::wstring line;

		while (!inputStream.eof()) {
			std::getline(inputStream, line);
			result.push_back(winrt::hstring{line}); 

			for (int32_t i = 0; i < whiteLines; ++i) {
				result.push_back(winrt::hstring{}); 
			}
		}
		return result;  
	}

	std::filesystem::path GetCacheFolder()
	{
		auto folder = winrt::Windows::Storage::ApplicationData::Current().LocalCacheFolder(); 
		std::filesystem::path result{ folder.Path().c_str()};
		result /= L"database"; 
		std::filesystem::create_directory(result); 
		return result; 
	}

	std::wstring SimpleHash(std::wstring input)
	{
		int sum = 0; 
		for (auto c : input) {
			sum += c;
		}

		std::wstring result = L"File_";
		result += std::to_wstring(sum); 
		return result; 
	}
}


